import cv2
import numpy as np
import os
from tqdm import tqdm  # 进度条工具（可选）

def normalize_image(image):
    """Min-Max 归一化到 [0, 1] 范围"""
    min_val = np.min(image)
    max_val = np.max(image)
    normalized = (image - min_val) / (max_val - min_val + 1e-10)  # 避免除以0
    return normalized

def image_diff(imgspath1, imgspath2, diffpath):
    """
    比较两个文件夹中的同名图片差异，保存差异图
    :param imgspath1: 第一个图片文件夹路径
    :param imgspath2: 第二个图片文件夹路径
    :param diffpath: 差异图保存路径
    """
    # 确保输出目录存在
    os.makedirs(diffpath, exist_ok=True)
    
    # 获取两个文件夹中共同存在的文件名
    files1 = set(os.listdir(imgspath1))
    files2 = set(os.listdir(imgspath2))
    common_files = files1 & files2
    
    for filename in tqdm(common_files):
        # 读取图片
        img1 = cv2.imread(os.path.join(imgspath1, filename))
        img2 = cv2.imread(os.path.join(imgspath2, filename))
        
        if img1 is None or img2 is None:
            print(f"警告：无法读取 {filename}，跳过")
            continue
            
        # 转换为 float32 并 Min-Max 归一化到 [0, 1]
        img1_norm = normalize_image(img1.astype(np.float32))
        img2_norm = normalize_image(img2.astype(np.float32))
        
        # 计算绝对差异并缩放回 [0, 255]
        diff = np.abs(img1_norm - img2_norm) * 255
        # diff = diff.clip(0, 255).astype(np.uint8)  # 确保值在合法范围内
        
        # 保存差异图
        output_path = os.path.join(diffpath, f"diff_{filename}")
        cv2.imwrite(output_path, diff)

# 使用示例
imgspath1 = R"Z:\tmp\lowhighfiff\low"  # 替换为实际路径
imgspath2 = R"Z:\tmp\lowhighfiff\high"  # 替换为实际路径
diffpath = R"Z:\tmp\lowhighfiff\diff3"  # 替换为实际路径
image_diff(imgspath1, imgspath2, diffpath)